<!doctypehtml><html class="sidebar-visible no-js light"lang=en><head><meta charset=UTF-8><title>Perl rename command - Perl One-Liners Guide</title><meta content="text/html; charset=utf-8"http-equiv=Content-Type><meta content="Example based guide for text processing with Perl from the command line"name=description><meta content=width=device-width,initial-scale=1 name=viewport><meta content=#ffffff name=theme-color><meta content="Perl One-Liners Guide"property=og:title><meta content=website property=og:type><meta content="Example based guide for text processing with Perl from the command line"property=og:description><meta content=https://learnbyexample.github.io/learn_perl_oneliners/ property=og:url><meta content=https://raw.githubusercontent.com/learnbyexample/learn_perl_oneliners/main/images/perl_oneliners_ls.png property=og:image><meta content=1280 property=og:image:width><meta content=720 property=og:image:height><meta content=summary_large_image property=twitter:card><meta content=@learn_byexample property=twitter:site><link href="favicon.svg" rel=icon><link rel="shortcut icon"href="favicon.png"><link href="css/variables.css" rel=stylesheet><link href="css/general.css" rel=stylesheet><link href="css/chrome.css" rel=stylesheet><link href="FontAwesome/css/font-awesome.css" rel=stylesheet><link href="fonts/fonts.css" rel=stylesheet><link href="highlight.css" rel=stylesheet><link href="tomorrow-night.css" rel=stylesheet><link href="ayu-highlight.css" rel=stylesheet><link href="style.css" rel=stylesheet><body><script>var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";</script><script>try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }</script><script>var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');</script><script>var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);</script><nav aria-label="Table of contents"class=sidebar id=sidebar><div class=sidebar-scrollbox><ol class=chapter><li class="chapter-item expanded affix"><a href="cover.html">Cover</a><li class="chapter-item expanded affix"><a href="buy.html">Buy PDF/EPUB versions</a><li class="chapter-item expanded"><a href="preface.html"><strong aria-hidden=true>1.</strong> Preface</a><li class="chapter-item expanded"><a href="one-liner-introduction.html"><strong aria-hidden=true>2.</strong> One-liner introduction</a><li class="chapter-item expanded"><a href="line-processing.html"><strong aria-hidden=true>3.</strong> Line processing</a><li class="chapter-item expanded"><a href="in-place-file-editing.html"><strong aria-hidden=true>4.</strong> In-place file editing</a><li class="chapter-item expanded"><a href="field-separators.html"><strong aria-hidden=true>5.</strong> Field separators</a><li class="chapter-item expanded"><a href="record-separators.html"><strong aria-hidden=true>6.</strong> Record separators</a><li class="chapter-item expanded"><a href="using-modules.html"><strong aria-hidden=true>7.</strong> Using modules</a><li class="chapter-item expanded"><a href="multiple-file-input.html"><strong aria-hidden=true>8.</strong> Multiple file input</a><li class="chapter-item expanded"><a href="processing-multiple-records.html"><strong aria-hidden=true>9.</strong> Processing multiple records</a><li class="chapter-item expanded"><a href="two-file-processing.html"><strong aria-hidden=true>10.</strong> Two file processing</a><li class="chapter-item expanded"><a href="dealing-with-duplicates.html"><strong aria-hidden=true>11.</strong> Dealing with duplicates</a><li class="chapter-item expanded"><a class=active href="perl-rename-command.html"><strong aria-hidden=true>12.</strong> Perl rename command</a><li class="chapter-item expanded"><a href="Exercise_solutions.html"><strong aria-hidden=true>13.</strong> Exercise Solutions</a></li><br><hr><li class="chapter-item expanded"><i class="fa fa-github"id=git-repository-button></i><a href=https://github.com/learnbyexample/learn_perl_oneliners>   Source code</a><li class="chapter-item expanded"><i class="fa fa-home"id=home-button></i><a href="../index.html">   My Blog</a><li class="chapter-item expanded"><i class="fa fa-book"id=book-button></i><a href="../books.html">   My Books</a><li class="chapter-item expanded"><i class="fa fa-envelope"id=mail-button></i><a href=https://learnbyexample.gumroad.com/l/learnbyexample-weekly>   learnbyexample weekly</a><li class="chapter-item expanded"><i class="fa fa-twitter"id=twitter-button></i><a href=https://twitter.com/learn_byexample>   Twitter</a></ol></div><div class=sidebar-resize-handle id=sidebar-resize-handle></div></nav><div class=page-wrapper id=page-wrapper><div class=page><div id=menu-bar-hover-placeholder></div><div class="menu-bar sticky bordered"id=menu-bar><div class=left-buttons><button aria-label="Toggle Table of Contents"title="Toggle Table of Contents"aria-controls=sidebar class=icon-button id=sidebar-toggle type=button><i class="fa fa-bars"></i></button><button aria-label="Change theme"title="Change theme"aria-controls=theme-list aria-expanded=false aria-haspopup=true class=icon-button id=theme-toggle type=button><i class="fa fa-paint-brush"></i></button><ul aria-label=Themes class=theme-popup id=theme-list role=menu><li role=none><button class=theme id=light role=menuitem>Light (default)</button><li role=none><button class=theme id=rust role=menuitem>Rust</button><li role=none><button class=theme id=coal role=menuitem>Coal</button><li role=none><button class=theme id=navy role=menuitem>Navy</button><li role=none><button class=theme id=ayu role=menuitem>Ayu</button></ul><button aria-label="Toggle Searchbar"title="Search. (Shortkey: s)"aria-controls=searchbar aria-expanded=false aria-keyshortcuts=S class=icon-button id=search-toggle type=button><i class="fa fa-search"></i></button></div><h1 class=menu-title>Perl One-Liners Guide</h1><div class=right-buttons><a aria-label=Blog href="../index.html" title=Blog> <i class="fa fa-home"id=home-button></i> </a><a aria-label=Twitter href=https://twitter.com/learn_byexample title=Twitter> <i class="fa fa-twitter"id=twitter-button></i> </a><a aria-label="Git repository"title="Git repository"href=https://github.com/learnbyexample/learn_perl_oneliners> <i class="fa fa-github"id=git-repository-button></i> </a></div></div><div class=hidden id=search-wrapper><form class=searchbar-outer id=searchbar-outer><input placeholder="Search this book ..."aria-controls=searchresults-outer aria-describedby=searchresults-header id=searchbar name=searchbar type=search></form><div class="searchresults-outer hidden"id=searchresults-outer><div class=searchresults-header id=searchresults-header></div><ul id=searchresults></ul></div></div><script>document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });</script><div class=content id=content><main><div class=sidetoc><nav class=pagetoc></nav></div><h1 id=perl-rename-command><a class=header href="perl-rename-command.html#perl-rename-command">Perl rename command</a></h1><p>This chapter will show a few examples for renaming files using the <code>rename</code> command. There are several implementations for this particular command. So, check <code>man rename</code> to see if you get the Perl based <code>rename</code> documentation as shown below:<pre><code class=language-bash>NAME
       rename - renames multiple files

SYNOPSIS
       rename [ -h|-m|-V ] [ -v ] [ -0 ] [ -n ] [ -f ] [ -d ]
       [ -e|-E perlexpr]*|perlexpr [ files ]

DESCRIPTION
       "rename" renames the filenames supplied according to the rule
       specified as the first argument.  The perlexpr argument is a
       Perl expression which is expected to modify the $_ string in
       Perl for at least some of the filenames specified.  If a given
       filename is not modified by the expression, it will not be
       renamed.  If no filenames are given on the command line,
       filenames will be read via standard input.
</code></pre><p>If you don't have the command installed, check your distribution's repository or you can install it from <a href=https://metacpan.org/pod/File::Rename>metacpan: File::Rename</a>. Here are couple of implementations on my system:<pre><code class=language-bash>$ rename --version
/usr/bin/rename using File::Rename version 1.10

$ rename.ul --version
rename.ul from util-linux 2.34
</code></pre><blockquote><p><img alt=info src="images/info.svg"> See also: <a href=https://askubuntu.com/questions/956010/whats-the-difference-between-the-different-rename-commands>askubuntu: What's the difference between the different "rename" commands?</a></blockquote><blockquote><p><img alt=info src="images/info.svg"> See also <a href=https://github.com/ayoisaiah/f2>F2: a cross-platform tool for batch renaming files and directories quickly and safely</a>.</blockquote><h2 id=basic-example-and-sanity-check><a class=header href="perl-rename-command.html#basic-example-and-sanity-check">Basic example and sanity check</a></h2><blockquote><p><img alt=info src="images/info.svg"> For this chapter, use an empty folder to follow along the examples presented. Delete the created files before moving on to the next illustration.</blockquote><p>The below example formats the filenames to consistently have three digits, so that the sorted filename display works for the numbers as well. The <code>-n</code> option allows you to do a sanity check without renaming the files.<pre><code class=language-bash>$ touch 1.png 3.png 25.png 100.png
$ ls
100.png  1.png  25.png  3.png

# sanity check
# note that 100.png isn't part of the output, since it isn't affected
$ rename -n 's/\d+/sprintf "%03d", $&/e' *.png
rename(1.png, 001.png)
rename(25.png, 025.png)
rename(3.png, 003.png)

# remove the -n option after sanity check to actually rename the files
$ rename 's/\d+/sprintf "%03d", $&/e' *.png
$ ls
001.png  003.png  025.png  100.png

$ rm *.png
</code></pre><blockquote><p><img alt=info src="images/info.svg"> For a more pleasing visual of the sanity check, pipe the output to <code>column -ts,</code> as shown below (assuming filenames don't have comma in them).<pre><code class=language-bash>$ rename -n 's/\d+/sprintf "%03d", $&/e' *.png | column -ts,
rename(1.png    001.png)
rename(25.png   025.png)
rename(3.png    003.png)
</code></pre></blockquote><h2 id=verbose-mode><a class=header href="perl-rename-command.html#verbose-mode">Verbose mode</a></h2><p>The <code>-v</code> option shows how the files have been renamed, similar to the <code>-n</code> option. The difference is that the <code>-v</code> option shows the result after the files have been renamed.<pre><code class=language-bash>$ touch a.b.c.d.txt 1.2.3.txt

# replace all dot characters except the extension
# sanity check
$ rename -n 's/\.(?=.*\.)/_/g' *.txt
rename(1.2.3.txt, 1_2_3.txt)
rename(a.b.c.d.txt, a_b_c_d.txt)
# verbose mode
$ rename -v 's/\.(?=.*\.)/_/g' *.txt
1.2.3.txt renamed as 1_2_3.txt
a.b.c.d.txt renamed as a_b_c_d.txt

$ ls
1_2_3.txt  a_b_c_d.txt

$ rm *.txt
</code></pre><h2 id=file-already-exists><a class=header href="perl-rename-command.html#file-already-exists">File already exists</a></h2><p>If a renaming operation matches a filename that already exists, such a renaming won't go through by default. You can override this behavior by using the <code>-f</code> option.<pre><code class=language-bash>$ touch report_v1.log report_v2.log

$ rename 's/v1/v2/' report_v1.log
report_v1.log not renamed: report_v2.log already exists
$ ls
report_v1.log  report_v2.log

$ rename -f 's/v1/v2/' report_v1.log
$ ls
report_v2.log

$ rm *.log
</code></pre><h2 id=rename-only-the-filename-component><a class=header href="perl-rename-command.html#rename-only-the-filename-component">Rename only the filename component</a></h2><p>If you are passing filenames with path components in them, use the <code>-d</code> option to affect only filename portion. Otherwise, the logic you are using might affect directory names as well.<pre><code class=language-bash>$ mkdir scripts
$ touch scripts/{toc.sh,reports.py}

# uppercase the first character of the filename
$ rename -n -d 's/./\u$&/' scripts/*
rename(scripts/reports.py, scripts/Reports.py)
rename(scripts/toc.sh, scripts/Toc.sh)

# without the -d option, directory name is affected
$ rename -n 's/./\u$&/' scripts/*
rename(scripts/reports.py, Scripts/reports.py)
rename(scripts/toc.sh, Scripts/toc.sh)

$ rm -r scripts
</code></pre><h2 id=incrementing-numbers><a class=header href="perl-rename-command.html#incrementing-numbers">Incrementing numbers</a></h2><p>Unlike the normal Perl one-liners, the <code>rename</code> command allows only <code>strict</code> mode. So, you'll have to declare variables before using them. However, you can cheat a little by using the <code>$a</code> and <code>$b</code> global variables (see <a href=https://stackoverflow.com/q/26127617/4082052>stackoverflow: Where do the $a and $b variables come from?</a> for details).<p>The below example replaces the first occurrence of numbers in the filename with an incrementing sequence.<pre><code class=language-bash>$ touch 1.png 3.png 25.png 100.png

$ rename -n 's/\d+/sprintf "%03d", ++$a/e' *.png
rename(100.png, 001.png)
rename(1.png, 002.png)
rename(25.png, 003.png)
rename(3.png, 004.png)

$ rm *.png
</code></pre><p>However, the above approach can lead to issues if a number already exists. You cannot use the <code>-f</code> option, since that'll lead to the file being overwritten instead of just being renamed. An example of such a problem is shown below.<pre><code class=language-bash>$ touch 1.png 3.png 25.png 100.png

$ rename -n 's/\d+/++$a/e' *.png
100.png not renamed: 1.png already exists
rename(1.png, 2.png)
25.png not renamed: 3.png already exists
rename(3.png, 4.png)

# oops, 2 files have disappeared!!
$ rename -f 's/\d+/++$a/e' *.png
$ ls
2.png  4.png

$ rm *.png
</code></pre><p>One of the ways to solve this issue is a two step process shown below. An extra unique string is added to the filenames, so that it cannot clash with existing filenames. The unique string is then removed afterwards.<pre><code class=language-bash>$ touch 1.png 3.png 25.png 100.png

$ rename -n 's/\d+/"op_" . ++$a/e' *.png
rename(100.png, op_1.png)
rename(1.png, op_2.png)
rename(25.png, op_3.png)
rename(3.png, op_4.png)

$ rename 's/\d+/"op_" . ++$a/e' *.png
$ rename 's/op_//' *.png

$ ls
1.png  2.png  3.png  4.png

$ rm *.png
</code></pre><h2 id=exercises><a class=header href="perl-rename-command.html#exercises">Exercises</a></h2><p><strong>1)</strong> Determine and implement the rename logic based on the filenames and expected output shown below.<pre><code class=language-bash>$ touch ' (2020) Report part 1 . txt ' 'analysis Part 3 (2018) .log'

##### add your solution here

$ ls
2020_report_part_1.txt  analysis_part_3_2018.log
</code></pre><p><strong>2)</strong> See <a href=https://unix.stackexchange.com/questions/tagged/rename?tab=Votes>unix.stackexchange: rename Q&A sorted by votes</a> for further reading as well as a source for exercises.</main><nav aria-label="Page navigation"class=nav-wrapper><a aria-label="Previous chapter"class="mobile-nav-chapters previous"title="Previous chapter"aria-keyshortcuts=Left href="dealing-with-duplicates.html" rel=prev> <i class="fa fa-angle-left"></i> </a><a aria-label="Next chapter"class="mobile-nav-chapters next"title="Next chapter"aria-keyshortcuts=Right href="Exercise_solutions.html" rel=next> <i class="fa fa-angle-right"></i> </a><div style="clear: both"></div></nav></div></div><nav aria-label="Page navigation"class=nav-wide-wrapper><a aria-label="Previous chapter"class="nav-chapters previous"title="Previous chapter"aria-keyshortcuts=Left href="dealing-with-duplicates.html" rel=prev> <i class="fa fa-angle-left"></i> </a><a aria-label="Next chapter"class="nav-chapters next"title="Next chapter"aria-keyshortcuts=Right href="Exercise_solutions.html" rel=next> <i class="fa fa-angle-right"></i> </a></nav></div><script>window.playground_copyable = true;</script><script charset=utf-8 src="elasticlunr.min.js"></script><script charset=utf-8 src="mark.min.js"></script><script charset=utf-8 src="searcher.js"></script><script charset=utf-8 src="clipboard.min.js"></script><script charset=utf-8 src="highlight.js"></script><script charset=utf-8 src="book.js"></script><script src="sidebar.js"></script>